package com.example.client;

import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.net.URI;

import com.fasterxml.jackson.core.JsonProcessingException;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import com.fasterxml.jackson.databind.ObjectMapper;

@ClientEndpoint
public class ClientController {
    /**
     * 显示我的名字
     */
    @FXML
    private Label showMyName;

    /**
     * 显示我的账号
     */
    @FXML
    private Label showMyAccount;

    /**
     * 聊天框上好友名字
     */
    @FXML
    private Label showFriendName;

    /**
     * 搜索输入框
     */
    @FXML
    private TextField textSearch;

    /**
     * 我的头像
     */
    @FXML
    private ImageView myImage;

    /**
     * 消息输入框
     */
    @FXML
    private TextArea textMsg;

    /**
     * 左侧放置好友
     */
    @FXML
    private VBox friendVBox;

    /**
     * 左侧放置好友的
     */
    @FXML
    private ScrollPane friendSCP;

    /**
     * 右侧放置聊天消息
     */
    @FXML
    private VBox msgVBox;

    /**
     * 右侧放置聊天消息的
     */
    @FXML
    private ScrollPane msgSCP;

    /**
     * 发送按钮
     */
    @FXML
    private Button btnSend;

    /**
     * 表情
     */
    @FXML
    private ImageView emoj;

    /**
     * 消息面板滚动条是否刷新
     */
    private boolean updateFlag = false;

    //每个客户的用户名
    private final String username = "hza";

    private Session session;
    private static final String WEBSOCKET_URI = "ws://139.9.185.3:8080/websocket/";

    public void initialize() throws IOException {
        connect();
    }

    @FXML
    private void clickImageButton(MouseEvent event) {

    }

    @FXML
    private void chooseEmojiButton(ActionEvent event) {

    }

    @FXML // 发送消息
    private void sendMessageButton(ActionEvent event) {
        sendMsg();
    }

    /**
     * 发送消息
     */
    void sendMsg() {
        //todo: 还要确定具体要发给谁
        Message msg = new Message(username, "ych", "", "TEXT", textMsg.getText());
        sendMessage(msg.toString());
        showSendMsg(textMsg.getText());
        System.out.println("发送消息：" + msg);
        updateFlag = true;
        msgSCP.setVvalue(1);
        this.textMsg.clear();
    }

    /**
     * 发消息
     * @param msg
     */
    void showSendMsg(String msg) {
        AnchorPane an = new AnchorPane();
        an.setPrefWidth(590);
        //ImageView iv = new ImageView(new Image("touxiang/u=1437473548,3272300633&fm=26&gp=0.jpg"));
        //iv.setFitWidth(40);
        //iv.setFitHeight(40);

        Label l1 = new Label(username);
        l1.setFont(new Font(13));
        l1.setTextAlignment(TextAlignment.RIGHT);
        l1.setMaxWidth(400);


        Label l2 = new Label(msg);
        l2.setFont(new Font(18));
        l2.setStyle("-fx-background-color: #ffffff");
        l2.setPadding(new Insets(5, 10, 5, 10));
        l2.setWrapText(true);
        l2.setMaxWidth(400);

        //an.getChildren().addAll(iv,l1,l2);
        an.getChildren().addAll(l1,l2);

        //AnchorPane.setLeftAnchor(iv, 537.0);
        //AnchorPane.setTopAnchor(iv, 25.0);

        AnchorPane.setRightAnchor(l1, 56.0);
        AnchorPane.setTopAnchor(l1, 25.0);

        AnchorPane.setRightAnchor(l2, 56.0);
        AnchorPane.setTopAnchor(l2, 55.0);

        msgVBox.getChildren().add(an);
    }

    /**
     * 收消息
     * @param msg
     */
    void showRecvMsg(Message msg) {
        Platform.runLater(() -> {
            AnchorPane an = new AnchorPane();
            an.setPrefWidth(590);
            //ImageView iv = new ImageView(new Image("touxiang/timg.jpg"));
            //iv.setFitWidth(40);
            //iv.setFitHeight(40);

            Label l1 = new Label(msg.getSender());
            l1.setFont(new Font(13));
            l1.setMaxWidth(400);

            Label l2 = new Label(msg.getMessage());
            l2.setFont(new Font(18));
            l2.setStyle("-fx-background-color: #55a3ec");
            l2.setPadding(new Insets(5, 10, 5, 10));
            l2.setMaxWidth(400);
            l2.setWrapText(true);

            //an.getChildren().addAll(iv,l1,l2);
            an.getChildren().addAll(l1,l2);

            //AnchorPane.setLeftAnchor(iv, 22.0);
            //AnchorPane.setTopAnchor(iv, 23.0);

            AnchorPane.setLeftAnchor(l1, 76.0);
            AnchorPane.setTopAnchor(l1, 23.0);

            AnchorPane.setLeftAnchor(l2, 76.0);
            AnchorPane.setTopAnchor(l2, 51.0);

            msgVBox.getChildren().add(an);
        });
    }

    /*下面是有关websocket的方法*/
    public void connect() {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            URI uri = URI.create(WEBSOCKET_URI + username);
            container.connectToServer(this, uri);
            System.out.println("连接成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String message) {
        try {
            if (session != null && session.isOpen()) {
                session.getBasicRemote().sendText(message);
            } else {
                System.out.println("Session is not open. Can't send message.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("Connected to the WebSocket server");
    }

    @OnMessage
    public void onMessage(String message) throws JsonProcessingException {
        System.out.println("Received message from server: " + message);

        ObjectMapper objectMapper = new ObjectMapper();
        Message msg = objectMapper.readValue(message, Message.class);
        if(username.equals(msg.getReceiver())){
            showRecvMsg(msg);
        }
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }
}
